package luweiteng.demoForLogin.service.impl;

import luweiteng.demoForLogin.common.utils.TokenUtils;
import luweiteng.demoForLogin.constant.RedisKey;
import luweiteng.demoForLogin.entity.TestUser;
import luweiteng.demoForLogin.service.TestUserService;
import luweiteng.demoForLogin.mapper.TestUserMapper;
import luweiteng.demoForLogin.vo.resp.DocUserResp;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.concurrent.TimeUnit;

@Service
public class TestUserServiceImpl implements TestUserService {


    @Autowired
    private TestUserMapper testUserMapper;

    @Autowired
    private RedissonClient redissonClient;


    @Override
    public DocUserResp getTestUser(TestUser user) {

        // 查询数据 是否存在
        TestUser testUser = testUserMapper.getUserInfo(user);
        Assert.notNull(testUser, "密码错误");
        //  把数据放入 Redis 中去
//        生成Token
        String token = TokenUtils.getToken();
//        根据Token 生成Tokenkey
        String tokenKey = String.format(RedisKey.DOC_USER_TOKEN, token);

        // 调用 RedissonClient
        redissonClient.getBucket(tokenKey).set(testUser, 30L, TimeUnit.DAYS);

        DocUserResp docUserInfo = new DocUserResp();
        BeanUtils.copyProperties(testUser, docUserInfo);
        docUserInfo.setToken(token);
        return docUserInfo;
    }

    @Override
    public TestUser getUserInfoByUserName(String userName) {
        Assert.notNull(userName, "UserName 不能为空！");
        return testUserMapper.getUserInfoByUserName(userName);
    }


}
